<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Session;
use think\Db;

/**
 * 销售管理
 *
 * @icon fa fa-circle-o
 */
class Salemanagement extends Backend
{
    
    /**
     * Salemanagement模型对象
     */
    protected $model = null;
    // 隐藏扩展字段
    protected $hiddenextendfield = true;

    /**
     * 是否开启数据限制
     * 支持auth/personal
     * 表示按权限判断/仅限个人 
     * 默认为禁用,若启用请务必保证表中存在admin_id字段
     */
    protected $dataLimit = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Salemanagement');
        $this->view->assign("salestatusList", $this->model->getSalestatusList());
        $this->view->assign("servicestateList", $this->model->getServicestateList());

        $this->view->assign('hiddenextendfield', $this->hiddenextendfield);
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill)
                {
                    $params[$this->dataLimitField] = $this->auth->id;
                    $params['acount'] = Session::get('admin')['username'];
                }
                try
                {
                    //是否采用模型验证
                    if ($this->modelValidate)
                    {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false)
                    {
                        $this->success();
                    }
                    else
                    {
                        $this->error($this->model->getError());
                    }
                }
                catch (\think\exception\PDOException $e)
                {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

     /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds))
        {
            if (!in_array($row[$this->dataLimitField], $adminIds))
            {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                try
                {
                    //是否采用模型验证
                    if ($this->modelValidate)
                    {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false)
                    {
                        $this->success();
                    }
                    else
                    {
                        $this->error($row->getError());
                    }
                }
                catch (\think\exception\PDOException $e)
                {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 导入
     */
    public function import()
    {   
        
        $file = $this->request->request('file');
      
        if (!$file)
        {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;

        //$filePath = 'G:\wamp\www\bstp-tp5\\public\/uploads/20180416/bccc0046070e87afb1daff75af2189cb.xlsx';
        
        if (!is_file($filePath))
        {
            $this->error(__('No results were found'));
        }
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath))
        {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath))
            {
                $PHPReader = new \PHPExcel_Reader_CSV();
                if (!$PHPReader->canRead($filePath))
                {
                    $this->error(__('Unknown data format'));
                }
            }
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v)
        {
            if ($importHeadType == 'comment')
            {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            }
            else
            {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }


        $PHPExcel = $PHPReader->load($filePath); //加载文件
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);
        for ($currentRow = 1; $currentRow <= 1; $currentRow++)
        {
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++)
            {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $fields[] = $val;
            }
        }


        $insert = [];
        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++)
        {
            $values = [];
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++)
            {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();

                $val = trim($val);
                // 从零开始计算列，第三列是销售时间
                if(3 == $currentColumn) {
                    if(empty($val)) {
                        $val = 0;
                    } else {
                        $val = ($val - 25569) * 24 * 60 * 60;
                        //$val = date('Y-m-d', $timestamp);
                    };
                    //_print($val);
                }
                // 从零开始计算列，第五列是销售状态
                if(5 == $currentColumn) {
                    switch ($val) {
                        case '未售':
                            $val = '0';
                            break;
                        case '已售':
                            $val = '1';
                            break;
                    }
                }

                // 从零开始计算列，第五列是状态值
                if(6 == $currentColumn) {
                    switch ($val) {
                        case '正常':
                            $val = '1';
                            break;
                        case '返修':
                            $val = '2';
                            break;
                        case '退货':
                            $val = '3';
                            break;
                    }
                }

                $values[] = is_null($val) ? '' : $val;
            }
            $row = [];
            $temp = array_combine($fields, $values);
            
            foreach ($temp as $k => $v)
            {
                if (isset($fieldArr[$k]) && $k !== '')
                {                    
                    $row[$fieldArr[$k]] = $v;
                }
            }
            if ($row)
            {   
                // 添加账号信息
                $row[$this->dataLimitField] = $this->auth->id;
                $row['acount'] = Session::get('admin')['username'];

                $insert[] = $row;
            }
        }
        if (!$insert)
        {
            $this->error(__('No rows were updated'));
        }
        try
        {   
            //dump($insert); //exit;
            // 遍历数组数据
            $_insertData = [];
            $_updateData = [];
            foreach($insert as $k => $v) {
                $v['instumentsno'] = trim($v['instumentsno']);
                if(empty($v['instumentsno'])) {
                    unset($insert[$k]);
                    continue;
                }
                $_insertData[$v['instumentsno']] = $v;
            }
            $_instrumentSnoData = array_keys($_insertData);            

            //dump($_instrumentSnoData); dump($_insertData);//exit;

            $_updateData = Db::name('salemanagement')->where('instumentsno', 'in', $_instrumentSnoData)->field('instumentsno, id')->select();
            //dump($_updateData);
            // 没有重复的Sno
            if(empty($_updateData)) {
                $this->model->saveAll($insert);
            } else {

                $_onlysnoarr = [];
                $_onlysnoidarr = [];
                foreach ($_updateData as $value) {
                    array_push($_onlysnoarr, $value['instumentsno']);
                    $_onlysnoidarr[$value['instumentsno']] = $value['id'];
                }
                unset($_updateData);                

                //dump( $_onlysnoarr);
                $kupdata = []; // 更新数据
                $kinsert = []; // 插入数据
                foreach($_insertData as $sno => $data) {
                    if(in_array($sno, $_onlysnoarr)) {
                        $data['id'] = $_onlysnoidarr[$sno];
                        $kupdata[] = $data; 
                    } else {
                        $kinsert[] = $data;
                    }
                }

                // 更新 
                //dump($kupdata);exit;
                $this->model->isUpdate()->saveAll($kupdata);
                // 新增
                //dump($kinsert);
                $this->model->insertAll($kinsert);
                //exit;
            }
            
        }
        catch (\think\exception\PDOException $exception)
        {
            $this->error($exception->getMessage());
        }

        $this->success();
    }

}
